package com.love.marriage.TecentIm.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.love.marriage.TecentIm.service.TencentImService;
import com.love.marriage.TecentIm.vo.ChatReadInfoVo;
import com.love.marriage.TecentIm.vo.RecentContactRequest;
import com.love.marriage.utils.UserSigUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TencentImServiceImp implements TencentImService {

    @Value("${tencent.im.sdkAppId}")
    private long sdkAppId;

    @Value("${tencent.im.secretKey}")
    private String secretKey;

    @Value("${tencent.im.adminAccount}")
    private String adminAccount;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String generateUserSig(String userId) {
        return UserSigUtil.generateUserSig(userId, secretKey, sdkAppId);
    }

    // 示例：通过 REST API 调用发送消息
    public String sendMessage(String fromUser, String toUser, String message) throws Exception {
        // 构建请求
        String url = "https://console.tim.qq.com/v4/openim/sendmsg?usersig=" + generateUserSig(adminAccount) + "&sdkappid=" + sdkAppId + "&identifier=" + adminAccount + "&random=99999999&contenttype=json";
        // 使用 RestTemplate 发送 HTTP 请求
        RestTemplate restTemplate = new RestTemplate();
        Map<String, Object> msgBodyItem = new HashMap<>();
        msgBodyItem.put("MsgType", "TIMTextElem");
        Map<String, Object> msgContent = new HashMap<>();
        msgContent.put("Text", message);  // 这里的 message 是
        msgBodyItem.put("MsgContent", msgContent);

        // 使用 List 来构建 MsgBody
        List<Map<String, Object>> msgBody = new ArrayList<>();
        msgBody.add(msgBodyItem);

        // 将 MsgBody 放入请求体
        Map<String, Object> request = new HashMap<>();
        request.put("From_Account", fromUser);
        request.put("To_Account", toUser);
        request.put("SyncOtherMachine", 1);  // 确保消息同步到对方所有终端，未读标记生效
        request.put("MsgLifeTime", 604800);
        request.put("MsgRandom", (int) (Math.random() * 4294967295L));  // 随机生成32位无符号整数
        request.put("MsgBody", msgBody);
        log.info("发送消息请求: {}", request);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        log.info("发送消息响应: {}", response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            return response.getBody();
        } else {
            throw new Exception("发送消息失败: ");
        }
    }

    @Override
    public String withdrawMessage(String fromAccount, String toAccount, String msgKey) throws Exception {
        String url = "https://console.tim.qq.com/v4/openim/admin_msgwithdraw?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("From_Account", fromAccount);
        requestBody.put("To_Account", toAccount);
        requestBody.put("MsgKey", msgKey);

        // 发送请求并处理响应
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCodeValue() == 200 && response.getBody() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
            if ("OK".equals(responseBody.get("ActionStatus"))) {
                return response.getBody();
            } else {
                throw new Exception("撤回消息失败，错误信息: " + responseBody.get("ErrorInfo"));
            }
        } else {
            throw new Exception("请求失败，响应状态码: " + response.getStatusCode());
        }
    }

    // 获取聊天记录并限制条数
    public String getChatHistory(String conversationId, int limit, long nextSeq, String userId) {
        String url = "https://console.tim.qq.com/v4/openim/admin_getroammsg?sdkappid=" + sdkAppId
                + "&identifier=" + userId + "&usersig=" + generateUserSig(userId)
                + "&random=" + Math.random() + "&contenttype=json";

        // 构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("ConversationID", conversationId);
        request.put("MaxCnt", limit);   // 限制每次拉取的消息数量
        request.put("NextMsgSeq", nextSeq);  // 下一次加载的序列号

        return restTemplate.postForObject(url, request, String.class);
    }

    // 获取会话列表
    public String getConversationList(String userId, int limit) {
        String url = "https://console.tim.qq.com/v4/openim/admin_getroammsg?sdkappid=" + sdkAppId
                + "&identifier=" + userId + "&usersig=" + generateUserSig(userId)
                + "&random=" + Math.random() + "&contenttype=json";

        // 构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("To_Account", userId);
        request.put("MaxCnt", limit);   // 限制获取的会话数量
        return restTemplate.postForObject(url, request, String.class);
    }

    // 获取用户消息记录
    public String getUserMessages(String fromUserId, String toUserId, long nextSeq, int limit) {
        String url = "https://console.tim.qq.com/v4/openim/admin_getroammsg?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + Math.random() + "&contenttype=json";

        // 构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("From_Account", fromUserId);  // 发送方用户ID
        request.put("To_Account", toUserId);      // 接收方用户ID
        request.put("MaxCnt", limit);             // 每次获取的消息数量
        request.put("MinTime", 0);                // 最早时间戳
        request.put("LastMsgKey", nextSeq);       // 分页时的消息 key

        return restTemplate.postForObject(url, request, String.class);
    }

    // 获取会话列表
    public String getRecentContacts(RecentContactRequest request) {
        String url = "https://console.tim.qq.com/v4/recentcontact/get_list?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)  // 随机生成32位无符号整数
                + "&contenttype=json";

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 构建请求体
        request.setAssistFlags(15);
        HttpEntity<RecentContactRequest> entity = new HttpEntity<>(request, headers);
        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return response.getBody();
    }

    // 调用 account_import 接口导入用户
    public Boolean importAccount(String userId, String nick, String faceUrl) {
        // 构造请求 URL
        String url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("UserID", userId);
        requestBody.put("Nick", nick);
        requestBody.put("FaceUrl", faceUrl);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("新建用户成功！");
            return true;
        } else {
            System.out.println("新建用户失败！");
            return false;
        }
    }

    public String getChatHistory(String operatorAccount, String peerAccount, long minTime, long maxTime, int maxCnt, String lastMsgKey) throws Exception {
        // 请求 URL
        String url = "https://console.tim.qq.com/v4/openim/admin_getroammsg?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("Operator_Account", operatorAccount);
        requestBody.put("Peer_Account", peerAccount);
        requestBody.put("MinTime", minTime);
        requestBody.put("MaxTime", maxTime);
        requestBody.put("MaxCnt", maxCnt);

        if (lastMsgKey != null && !lastMsgKey.isEmpty()) {
            requestBody.put("LastMsgKey", lastMsgKey);  // 续拉时使用
        }
        // 发送 POST 请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            // 使用 ObjectMapper 将响应体解析为 Map
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);

            // 检查响应体中的 "ActionStatus" 字段
            if ("OK".equals(responseBody.get("ActionStatus"))) {
                System.out.println("查询聊天记录成功！");
                return response.getBody();  // 返回原始的 JSON 字符串
            } else {
                throw new Exception("查询聊天记录失败，原因: " + responseBody.get("ErrorInfo"));
            }
        } else {
            throw new Exception("查询聊天记录失败，响应状态码: " + response.getStatusCode());
        }
    }

    @Override
    public Map<String, Object> getBatchUnreadMessageCount(String toAccount, String[] peerAccounts) throws Exception {
        String url = "https://console.tim.qq.com/v4/openim/get_c2c_unread_msg_num?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("To_Account", toAccount);
        requestBody.put("Peer_Account", peerAccounts);
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCodeValue() == 200 && response.getBody() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
            if ("OK".equals(responseBody.get("ActionStatus"))) {
                return responseBody;
            } else {
                throw new Exception("查询未读消息失败，错误信息: " + responseBody.get("ErrorInfo"));
            }
        } else {
            throw new Exception("请求失败，响应状态码: " + response.getStatusCode());
        }
    }

    @Override
    public Map<String, Object> sendReadReceipt(String operatorAccount, String peerAccount, List<ChatReadInfoVo> chatReadInfoVoList) throws Exception {
        if (chatReadInfoVoList == null || chatReadInfoVoList.isEmpty()) {
            throw new Exception("发送已读回执失败，消息列表为空");
        }

        String url = "https://console.tim.qq.com/v4/openim/c2c_msg_read_receipt?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("Operator_Account", operatorAccount);
        requestBody.put("Peer_Account", peerAccount);

        List<Map<String, Object>> c2cMsgInfoList = chatReadInfoVoList.stream().map(item -> {
            Map<String, Object> c2cMsgInfo = new HashMap<>();
            c2cMsgInfo.put("From_Account", item.getPeerAccount().toString());
            c2cMsgInfo.put("To_Account", item.getOperatorAccount().toString());
            c2cMsgInfo.put("MsgKey", item.getMsgKey());
            return c2cMsgInfo;
        }).collect(Collectors.toList());
        requestBody.put("C2CMsgInfo", c2cMsgInfoList);

        // 发送请求并处理响应
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCodeValue() == 200 && response.getBody() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
            log.info("requestBody:{}, 消息已读返回结果：{}", requestBody, responseBody);
            if ("OK".equals(responseBody.get("ActionStatus"))) {
                return responseBody;
            } else {
                throw new Exception("发送已读回执失败，错误信息: " + responseBody.get("ErrorInfo"));
            }
        } else {
            throw new Exception("请求失败，响应状态码: " + response.getStatusCode());
        }
    }

    @Override
    public Boolean deleteChatMessages(String operatorAccount, String peerAccount, List<String> msgKeyList) throws Exception {
        // 构建请求 URL
        String url = "https://console.tim.qq.com/v4/openim/delete_c2c_msg_ramble?sdkappid=" + sdkAppId
                + "&identifier=" + adminAccount
                + "&usersig=" + generateUserSig(adminAccount)
                + "&random=" + (int) (Math.random() * 4294967295L)
                + "&contenttype=json";

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("Operator_Account", operatorAccount);
        requestBody.put("Peer_Account", peerAccount);
        requestBody.put("MsgKeyList", msgKeyList);

        // 发送请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
        if (response.getStatusCodeValue() == 200 && response.getBody() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
            log.info("requestBody:{}, 删除消息返回结果：{}", requestBody, responseBody);
            if ("OK".equals(responseBody.get("ActionStatus"))) {
                return true;
            } else {
                throw new Exception("删除消息失败，错误信息: " + responseBody.get("ErrorInfo"));
            }
        } else {
            throw new Exception("请求失败，响应状态码: " + response.getStatusCode());
        }
    }

    @Override
    public String sage(String fromUser, String toUser, String message) throws Exception {
        return null;
    }
}
